package server.main.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.stereotype.Service;
import server.main.mapper.*;
import server.main.pojo.*;
import server.main.service.AccountService;
import server.main.utils.DateUtils;

import java.util.*;

/**
 * @auther MingHsZzz
 * @create 2022-08-26-14:55
 */


@Service("AccountService")
public class AccountServiceImpl  extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    AccountService accountService;


    @Autowired
    AccountMapper accountMapper;

    @Autowired
    FunctionPageMapper functionPageMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    DoctorMapper doctorMapper;

    @Autowired
    AccountRoleMapper accountRoleMapper;

    @Override
    public boolean saveper(JSONObject json) {

        Account user = accountService.getOne(
                new LambdaUpdateWrapper<Account>().eq(Account::getUsername, json.get("username"))
        );
        System.out.println(user);
        user.setPersonalization(json.getString("personalization"));
        user.setGmtModified(DateUtils.getNowDatetime());
        return accountService.updateById(user);
    }

    @Override
    public boolean register(String jobnum,String password) {
        Date nowDatetime = DateUtils.getNowDatetime();
//        JSONObject json = JSON.parseObject(jsonString);
        if(accountService.getOne(
                new LambdaQueryWrapper<Account>().eq(Account::getUsername,jobnum)
                        .or()
                        .eq(Account::getJobnum,jobnum)
        ) != null){
            throw new DisabledException("用户已存在，请核实工号");
        }
        Account account = new Account();
        account.setUsername(jobnum);
        account.setJobnum(jobnum);
        account.setPassword(password);
        account.setGmtModified(nowDatetime);
        account.setGmtCreate(nowDatetime);
        account.setPersonalization("{\"asideFold\":false,\"mainTabsHeaderFixed\":true,\"asideControlOpen\":true,\"headerSkin\":\"colorful\",\"headerFixed\":false,\"skin\":\"gray\",\"asideSkin\":\"dark\",\"asideControlFixed\":true}");
        account.setVersion(1);

        accountMapper.insert(account);


        return true;
    }

    @Override
    public String getMenuJsonString(String jobnum) {
        Map<String,List<FunctionPage>> map = new HashMap<>();
        List<FunctionPage> userMenu = getFunctionPages(jobnum);
//        List<FunctionPage> userMenu = functionPageMapper.getall();

        for (FunctionPage menu : userMenu) {

            if(menu != null && !menu.getTitle().equals("none")){
                if(!map.containsKey(menu.getTitle() + "_" + menu.getTitleflag())){
                    map.put(menu.getTitle() + "_" + menu.getTitleflag(),new ArrayList<FunctionPage>());
                }
                map.get(menu.getTitle() + "_" + menu.getTitleflag()).add(menu);
            }
//            System.out.println(map);
        }

        /**
         * 结构是：{
         *            "titleflag" :
         *            "title":
         *            "pages":[
         *                functionpage的json对象
         *            ]
         *        }
         */
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> functions = new ArrayList<>();

        for (String s : map.keySet()) {
            JSONObject json1 = new JSONObject();
            json1.put("titleflag",s.split("_")[1]);
            json1.put("title",s.split("_")[0]);
            List<JSONObject> urls = new ArrayList<>();
            for (FunctionPage functionPage : map.get(s)) {
                System.out.println(functionPage);
                JSONObject json2 = JSONObject.parseObject(JSONObject.toJSONString(functionPage));
                json2.put("id",json2.get("id").toString());
                urls.add(json2);
//                System.out.println(json2.toJSONString());

            }
            json1.put("urls",urls);
            functions.add(json1);
        }
        jsonObject.put("menu",functions);
        System.out.println(jsonObject.toJSONString());


        return jsonObject.toJSONString();
    }

    @Override
    public List<FunctionPage> getFunctionPages(String jobnum) {
        List<Role> roles = roleMapper.gettole(jobnum);
        System.out.println(roles);

        List<FunctionPage> functionPages = new ArrayList<>();
        //不同角色的去同
        for (Role role : roles) {
            for (FunctionPage userMenu : functionPageMapper.getUserMenu(role.getId())) {
                if(!functionPages.contains(userMenu)){
                    functionPages.add(userMenu);
                }
            }
        }



        return functionPages;
    }

    @Override
    public Page<Account> getCompleteAccMsgByPage(String jobnum, Integer pageNum,Integer pageSize){

//        Account account = accountMapper.loadUserByJobnum(jobnum);
        Page<Account> page = page(new Page<>(pageNum, pageSize));

        for (Account record : page.getRecords()) {
            record.setDoctor(doctorMapper.getDoctor(record.getJobnum()));
            record.setRoles(roleMapper.gettole(record.getJobnum()));
        }
        System.out.println("getCompleteAccMsgByPage: " + page.getRecords().toString());
//        System.out.println(JSONObject.parse(page.getRecords().toString()));



        return page;
    }

    @Override
    public boolean saveAccountRole(List<AccountRole> accountRoles) {

        for (AccountRole accountRole : accountRoles) {
            accountRoleMapper.insert(accountRole);
        }


        return true;
    }

    @Override
    public boolean deleteAccountByJonbnum(String jobnum) {
        accountRoleMapper.deleterole(jobnum);

        accountMapper.deleteByJobnum(jobnum);

        return true;
    }


}
